//JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式，易于读写,
//相对于XML来说JSON格式的字符串占用带宽更小。
//运行以下代码需下载jar包(http://json-lib.sourceforge.net/)

/*
 * 用法：
   如果json串以"["开头，则 JSONArray jsonArray = JSONArray.fromObject(jsonText);
   如果josn串以"{"开头，则 JSONObject obj = JSONObject.fromObject(jsonText);

   在内部
   如果"["里面包含"{"，则 
    JSONObject obj = (JSONObject) jsonArray.get(Index);//根据索引拿到数组中的object
   如果"{"里面包含"["，则
    JSONArray arr = obj.getJSONArray("arrName");//根据数据名从obj里拿到数组 arr

 *
 */

 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
 
public class JsonExample {
    public static void main(String[] args) throws Exception {
       //为了数据显示清楚，所以使用String拼写Json字符串
       String jsonText = "[" +
                         "{" +
                            "'author':'lijingcheng'," +
                            "'male':true," +
                            "'age':27," +
                            "'money':null," +
                            "'blog':'http://blog.sina.com/lijingcheng1984'," +
                            "'email':" +
                            "{" +
                                "'gmail':'bj.lijingcheng@gmail.com'," +
                                "'163':'bj_lijingcheng@163.com'," +
                            "}," +
                            "'phone':" +
                            "[" +
                                "{" +
                                   "'brand':'sansung'," +
                                   "'model':'i9000'," +
                                "}," +
                                "{" +
                                   "'brand':'apple'," +
                                   "'model':'iPhone4'," +
                                "}" +
                            "]" +
                         "}" +
                     "]";
       JSONArray jsonArray = JSONArray.fromObject(jsonText);
 
       for (int i = 0; i < jsonArray.size(); i++) {
           JSONObject obj = (JSONObject) jsonArray.get(i);
           System.out.println(obj.getString("author"));
           System.out.println(obj.getBoolean("male"));
           System.out.println(obj.getInt("age"));
           System.out.println(obj.get("money"));
           System.out.println(obj.getString("blog"));
 
           JSONObject email = (JSONObject) obj.getJSONObject("email");
           System.out.println(email.get("gmail") + ", "
                  + email.getString("163"));
 
           JSONArray phone = obj.getJSONArray("phone");
           for (int j = 0; j < phone.size(); j++) {
              JSONObject temp = (JSONObject) phone.get(j);
              System.out.println(temp.getString("brand") + ", "
                     + temp.getString("model"));
           }
       }
    }
}